import React from 'react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { FolderOpen } from 'lucide-react'
import { toast } from 'sonner'

interface FileSelectorProps {
  id?: string
  label: string
  value: string | null
  onChange: (value: string) => void
  onSelectFile: () => void
  placeholder?: string
  className?: string
  labelClassName?: string
}

const FileSelector: React.FC<FileSelectorProps> = ({
  id,
  label,
  value,
  onChange,
  onSelectFile,
  placeholder = '请点击选择文件',
  className = '',
  labelClassName = 'min-w-[90px]'
}) => {
  return (
    <div className={`flex items-center gap-2 ${className}`}>
      <Label htmlFor={id} className={labelClassName}>
        {label}
      </Label>
      <div className="flex-grow relative">
        <Input
          id={id}
          placeholder={placeholder}
          value={value ?? ''}
          onChange={(e) => onChange(e.target.value)}
          onBlur={(e) => {
            const value = e.target.value
            // 简单判断是否像路径格式 (包含斜杠或反斜杠)
            const isPath = /[/\\]/.test(value) || /^\w:[/\\]/.test(value)
            if (!(isPath || value === '')) {
              toast.warning('请输入有效的文件路径')
            }
          }}
          className="pr-10"
        />
        <Button
          variant="ghost"
          size="icon"
          onClick={onSelectFile}
          title="选择文件"
          className="absolute right-0 top-0 h-full"
        >
          <FolderOpen className="h-4 w-4" />
        </Button>
      </div>
    </div>
  )
}

export default FileSelector
